# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '23/05/2023'
    comment: 设备推送
"""
import asyncio
import ujson
from project.model.database.cariabot import DeviceJpush
from project.middleware.jpush import JPush
from project.lib.common import async_session, AsyncScopedSession

# 侧边栏刷新
CARIABOT_COLUMN_FLUSH = 'cariabot_column_flush'
# 服务流程刷新
FLOW_FLUSH = 'flow_flush'
# 流程节点刷新
NODE_FLUSH = 'node_flush'


class JpushService:
    """
    """
    @staticmethod
    async def push(session, organization_code, flow_code='', node_code='', _type=''):
        """
        """
        title = ''
        content = {}
        if _type == CARIABOT_COLUMN_FLUSH:
            title = '侧边栏刷新'
            content = {'action': CARIABOT_COLUMN_FLUSH}
        elif _type == FLOW_FLUSH:
            title = '服务流程刷新'
            content = {'action': FLOW_FLUSH, 'flow_code': flow_code}
        elif _type == NODE_FLUSH:
            title = '流程节点刷新'
            content = {'action': NODE_FLUSH, 'flow_code': flow_code, 'node_code': node_code}

        if not title:
            return

        devices = await DeviceJpush.fetch_all(session, wheres=(DeviceJpush.organization_code == organization_code))
        for device in devices:
            if not device.registration_id:
                continue

            # 极光推送
            JPush.send(device.registration_id, ujson.dumps(content), title)


async def main():
    async with AsyncScopedSession(async_session) as session:
        await JpushService.push(session, organization_code='NSZY01', _type=NODE_FLUSH)


if __name__ == "__main__":

    asyncio.run(main())

